package com.web.estate.common;

import static com.web.estate.common.Constants.COOKIE_LOGIN_ID;
import static com.web.estate.common.Constants.COOKIE_USER_ID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.web.estate.domain.UserDO;

@Component
public class CookieUtil {

	@Value("${cookie.domain}")
	private String domain;

	public boolean isLogin(HttpServletRequest req) {
		Cookie[] cookies = req.getCookies();
		if (ArrayUtils.isNotEmpty(cookies)) {
			for (Cookie cookie : cookies) {
				if (COOKIE_LOGIN_ID.equals(cookie.getName()) && StringUtils.isNotBlank(cookie.getValue())
						&& domain.equals(cookie.getDomain())) {
					return true;
				}
			}
		}

		return false;
	}

	public void writeCookie(UserDO user, HttpServletResponse resp) {
		if (user != null) {
			resp.addCookie(getCookie(COOKIE_USER_ID, String.valueOf(user.getId())));
			resp.addCookie(getCookie(COOKIE_LOGIN_ID, String.valueOf(user.getLoginId())));
		}
	}

	private Cookie getCookie(String name, String value) {
		Cookie cookie = new Cookie(name, value);
		cookie.setDomain(domain);
		cookie.setPath("/");
		cookie.setMaxAge(-1);
		return cookie;
	}
}
